/** 
 * @Description: 文件描述
 * @Author: 程前
 * @Date: 2025-02-25 15:11:06
 * @LastEditors: 程前
 * @LastEditTime: 2025-02-26 17:01:43
 */
import { Viewer, Entity, Cartesian3, Color, Primitive, Material, GeometryInstance, EllipsoidSurfaceAppearance, PolygonHierarchy, PolygonGeometry, Cartographic, Math as CesiumMath, sampleTerrainMostDetailed } from "cesium";
import { useDrawRiver } from "../../tool/analysis/flood/waterPrimitive";
import { getAssetsFile } from "@/utils";

export interface WaterDemoOptions {
    viewer: Viewer;
    coordinates: Cartesian3[];
    color?: Color;
    speed?: number;
    waterImg?: string;

}

export class WaterDemo {
    private viewer: Viewer;
    private coordinates: Cartesian3[];
    private color: Color;
    private speed: number;
    private waterImg?: string;


    private minHeight: number = 0;
    private maxHeight: number = 0;
    private currentHeight: number = 0;
    private animationInterval: NodeJS.Timeout | null = null;
    private waterPrimitive: any = null;
    private isAnalyzing: boolean = false;

    constructor(options: WaterDemoOptions) {
        this.viewer = options.viewer;
        this.coordinates = options.coordinates;
        this.color = options.color ?? Color.fromBytes(64, 157, 253);
        this.speed = options.speed ?? 2.0;
        this.waterImg = options.waterImg ?? getAssetsFile("cesium/waterNormal-1.jpg");

        // 重置所有状态
        this.minHeight = 0;
        this.maxHeight = 0;
        this.currentHeight = 0;
        this.isAnalyzing = false;

        // 启用地形深度测试
        this.viewer.scene.globe.depthTestAgainstTerrain = true;

        // 计算高度范围并创建水面
        this.calculateHeightRange();
    }

    private calculateHeightRange(): void {
        // 创建水面
        if (this.waterPrimitive) {
            const primitiveCollection = this.viewer.scene.primitives;
            primitiveCollection.remove(this.waterPrimitive);
            this.waterPrimitive = null;
        }
        this.createWaterPrimitive();

    }

    private createWaterPrimitive(): void {
        try {
            // 将Cartesian3坐标转换为经纬度数组
            const boundary: number[] = [];
            this.coordinates.forEach(coord => {
                const cartographic = Cartographic.fromCartesian(coord);
                if (isNaN(cartographic.longitude) || isNaN(cartographic.latitude)) {
                    return;
                }
                const lon = CesiumMath.toDegrees(cartographic.longitude);
                const lat = CesiumMath.toDegrees(cartographic.latitude);
                if (isNaN(lon) || isNaN(lat)) {
                    return;
                }
                boundary.push(lon);
                boundary.push(lat);
            });

            // 检查边界点是否足够
            if (boundary.length < 6) { // 至少需要3个点（6个数值）
                return;
            }


            // 创建水面材质
            const riverMaterial = new Material({
                fabric: {
                    type: "Water",
                    uniforms: {
                        blendColor: new Color(0.0, 0.0, 1.0, 0.2),
                        normalMap: this.waterImg,
                        frequency: 500.0,
                        animationSpeed: 0.05,
                        amplitude: 10.0
                    }
                }
            });

            // 创建水面函数
            const createRiverPrimitive = (height: number) => {
                const polygon = this.useCreatePolygonGeometry(boundary, height);
                if (!polygon) return null;

                const primitive = new Primitive({
                    geometryInstances: new GeometryInstance({
                        geometry: polygon,
                    }),
                    appearance: new EllipsoidSurfaceAppearance({
                        aboveGround: true,
                    }),
                    show: true,
                    asynchronous: false,
                    releaseGeometryInstances: false,
                });

                primitive.appearance.material = riverMaterial;
                return primitive;
            };
            createRiverPrimitive(500)
        } catch (error) {
        }
    }


    useCreatePolygonGeometry(boundary: number[], extrudedHeight: number) {
        try {
            // 验证参数
            if (!boundary || boundary.length < 6 || typeof extrudedHeight !== 'number' || isNaN(extrudedHeight)) {
                return null;
            }

            const polygon = new PolygonGeometry({
                polygonHierarchy: new PolygonHierarchy(Cartesian3.fromDegreesArray(boundary)),
                extrudedHeight,
                vertexFormat: EllipsoidSurfaceAppearance.VERTEX_FORMAT,
            });

            return polygon;
        } catch (error) {
            console.error(error);
            return null;
        }
    };
    public destroy(): void {
        if (this.waterPrimitive) {
            // 调用水面代理对象的 destroy 方法清理所有资源
            this.waterPrimitive.destroy();
            this.waterPrimitive = null;
        }
    }
}

